package com.itheima.wallet.web.Controller;

import com.itheima.wallet.user.api.UserLoginServiceApi;
import com.itheima.wallet.user.api.UserRegisterServiceApi;
import com.itheima.wallet.user.api.UserSendSmsServiceApi;
import com.itheima.wallet.user.vo.ErrorResult;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class SmsController {
    //注入service层
    @Reference(version = "1.0.0")
    private UserSendSmsServiceApi userSendSmsService;

    @Reference(version = "1.0.0")
    private UserLoginServiceApi userLoginServiceApi;

    @Reference(version = "1.0.0")
    private UserRegisterServiceApi userRegisterServiceApi;

    /**
     * 获取验证码的接口
     * @param param
     * @return
     */
    @PostMapping("/send")
    public ResponseEntity<ErrorResult> sendCodeAndCheck(@RequestBody Map<String,String>param){
        String phone = param.get("phone");
        ErrorResult errorResult = this.userSendSmsService.sendCheckCode(phone);
        if(null == errorResult){
            ResponseEntity<ErrorResult> entity = ResponseEntity.ok(null);
            return entity;
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }


    /**
     * 用户登录的方法
     * @param param 手机号
     *
     * @return 返回的token
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map<String,String>param){
        String phone = param.get("phone");
        String code = param.get("code");
        String resultsStr = this.userLoginServiceApi.login(phone, code);
        if(null!=resultsStr){
            Map<String,String> result = new HashMap<>();
            result.put("token",resultsStr);
            return ResponseEntity.ok(result);
        }

        return  null;
    }

    @PostMapping("/register")
    public ResponseEntity saveUserInfo(@RequestBody Map<String,String>param){
        ErrorResult errorResult = this.userRegisterServiceApi.saveUserInfo(param);
        if (errorResult== null){
            return ResponseEntity.ok("注册成功");
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();

    }
}
